package br.progweb.webapp.controller;

import br.progweb.webapp.model.Contato;
import br.progweb.webapp.model.Grupo;
import br.progweb.webapp.service.ContatoManager;
import br.progweb.webapp.service.GrupoManager;
import br.progweb.webapp.util.Gravatar;
import br.progweb.webapp.util.customeditor.GroupCustomEditor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: luiza
 * Date: 05/09/12
 * Time: 00:58
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/contatoForm*")
public class ContatoFormController extends BaseFormController {
// ------------------------------ FIELDS ------------------------------

    @Autowired
    ContatoManager contatoManager;

    @Autowired
    GrupoManager grupoManager;

    @Autowired
    GroupCustomEditor groupCustomEditor;

// -------------------------- OTHER METHODS --------------------------

    @ModelAttribute
    @RequestMapping(method = RequestMethod.GET)
    protected Contato getContato(HttpServletRequest request, ModelMap model) {
        String contatoId = request.getParameter("id");
        model.addAttribute("grupoList", grupoManager.getGrupos());
        if ((contatoId != null) && !contatoId.equals("")) {
            return contatoManager.get(Long.parseLong(contatoId));
        } else {
            return new Contato();
        }
    }

    /**
     * Set up a custom property editor para converter Longs
     *
     * @param binder the default databinder
     */
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        // convert java.util.Date
        SimpleDateFormat dateFormat = new SimpleDateFormat(getText("date.format"));
            dateFormat.setLenient(false);

        binder.registerCustomEditor(Date.class, null,
                new CustomDateEditor(dateFormat, true));

        // convert java.lang.Long
        binder.registerCustomEditor(Long.class, null,
                new CustomNumberEditor(Long.class, null, true));

        binder.registerCustomEditor(Grupo.class, null,
                new CustomNumberEditor(Long.class, null, true));

        binder.registerCustomEditor(Grupo.class, null, groupCustomEditor);
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(Contato contato, BindingResult result, HttpServletRequest request) throws Exception {
        if (request.getParameter("cancel") != null)
            return "redirect:contatos";


        if (validator != null) { // validator is null during testing
            validator.validate(contato, result);

            if (result.hasErrors()) {
                return "contatoForm";
            }
        }

        log.debug("entrando metodo 'onSubmit' ");

        if (request.getParameter("delete") != null) {
            contatoManager.removeContato(contato);
            request.getSession().setAttribute("message",
                    getText("contato.deleted", contato.getNome()));
        } else {
            //Gravatar
            contato.setGravatarURL(new Gravatar().getUrl(contato.getEmail(), Gravatar.GravatarURLType.AVATAR));

            contatoManager.saveContato(contato);
            request.getSession().setAttribute("message",
                    getText("contato.saved", contato.getNome()));
        }

        return "redirect:contatos";
    }
}
